﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace File_Operate_Program
{
    public partial class FrmCSV_Editor : Form
    {
        IniFiles ini;
        static Singleton singleton = Singleton._instance;
        public CCurrentCSVFile cCurrentCSVFile = new CCurrentCSVFile();

        public FrmCSV_Editor()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void FrmCSV_Operate_Load(object sender, EventArgs e)
        {
            ini = new IniFiles(singleton.ConfigIniPath);
            string sCBBDataEncoding = ini.IniReadValue("FrmCSV_Editor", "sCBBDataEncoding");
            if (!string.IsNullOrEmpty(sCBBDataEncoding))
            {
                string[] sArrayEncodings = sCBBDataEncoding.Split(',');

                foreach (var sArrayEncodingsItem in sArrayEncodings)
                {
                    CBBDataEncoding.Items.Add(sArrayEncodingsItem);
                }
                CBBDataEncoding.Text = sArrayEncodings[0];
            }

            #region 方法赋值
            this.BtnOpenFile.Click += new System.EventHandler(this.BtnOpenFile_Click);
            this.BtnAddRow.Click += new System.EventHandler(this.BtnAddRow_Click);
            this.BtnAddColumn.Click += new System.EventHandler(this.BtnAddColumn_Click);
            this.BtnDelRow.Click += new System.EventHandler(this.BtnDelRow_Click);
            this.BtnDelColumn.Click += new System.EventHandler(this.BtnDelColumn_Click);
            this.DGVFileData.KeyDown += new System.Windows.Forms.KeyEventHandler(this.DGVFileData_KeyDown);
            this.BtnGetCEncodingList.Click += new System.EventHandler(this.BtnGetCEncodingList_Click);
            this.CBSelectAll.CheckedChanged += new System.EventHandler(this.CBSelectAll_CheckedChanged);
            this.BtnSelectKeyWord.Click += new System.EventHandler(this.BtnSelectKeyWord_Click);
            this.BtnNewFile.Click += new System.EventHandler(this.BtnNewFile_Click);
            this.BtnSaveFile.Click += new System.EventHandler(this.BtnSaveFile_Click);
            this.BtnSaveAsFile.Click += new System.EventHandler(this.BtnSaveAsFile_Click);
            this.TxtSelectKeyWord.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TxtSelectKeyWord_KeyPress);
            this.新建文件ToolStripMenuItem1.Click += new System.EventHandler(this.新建文件ToolStripMenuItem1_Click);
            this.打开文件ToolStripMenuItem.Click += new System.EventHandler(this.打开文件ToolStripMenuItem_Click);
            this.保存文件ToolStripMenuItem.Click += new System.EventHandler(this.保存文件ToolStripMenuItem_Click);
            this.另存为文件ToolStripMenuItem.Click += new System.EventHandler(this.另存为文件ToolStripMenuItem_Click);
            this.BtnShowOriginalData.Click += new System.EventHandler(this.BtnShowOriginalData_Click);
            this.LVSelectKeyWord.SelectedIndexChanged += new System.EventHandler(this.LVSelectKeyWord_SelectedIndexChanged);
            this.TxtRowNum.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TxtRowNum_KeyPress);
            this.BtnRowNum.Click += new System.EventHandler(this.BtnRowNum_Click);
            #endregion

            #region 表格属性
            DGVFileData.AllowUserToAddRows = false;
            #endregion

            #region 测试按钮属性
            BtnGetCEncodingList.Visible = false;
            #endregion

            #region ListView属性
            LVSelectKeyWord.View = View.Details;
            LVSelectKeyWord.GridLines = true;
            LVSelectKeyWord.FullRowSelect = true;
            LVSelectKeyWord.MultiSelect = false;

            LVSelectKeyWord.Columns.Add("序号", 70, HorizontalAlignment.Left);
            LVSelectKeyWord.Columns.Add("列名", 100, HorizontalAlignment.Left);
            LVSelectKeyWord.Columns.Add("行号", 70, HorizontalAlignment.Left);
            #endregion
        }

        private void BtnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFile();
        }

        private void OpenFile()
        {
            OpenFileDialog openfile = new OpenFileDialog();
            string sOpenFileInitlDir = ini.IniReadValue("FrmCSV_Editor", "sOpenFileInitlDir");
            if (!string.IsNullOrEmpty(sOpenFileInitlDir))
            {
                openfile.InitialDirectory = sOpenFileInitlDir;
            }
            else
            {
                openfile.InitialDirectory = singleton.FilePath;
            }

            openfile.Title = "请选择文件";
            openfile.Filter = "文本文件|*.csv";
            if (DialogResult.OK == openfile.ShowDialog())
            {
                RTxtFileInfo.Clear();

                string sFilePath = openfile.FileName;
                Encoding TxtEncoding = CCSV_Operate.GetType(sFilePath);  //get encode from document . 

                RTxtFileInfo.AppendText($"文件路径：{ sFilePath }\n");
                if (TxtEncoding.HeaderName.Contains("utf-8"))
                {
                    var TxtEncodingGetPreamble = TxtEncoding.GetPreamble();
                    if (TxtEncodingGetPreamble.Length != 0 && (TxtEncodingGetPreamble[0] == 0xEF && TxtEncodingGetPreamble[1] == 0xBB && TxtEncodingGetPreamble[2] == 0xBF))
                    {
                        RTxtFileInfo.AppendText($"文件类型：UTF-8-BOM\n");
                    }
                    else
                    {
                        RTxtFileInfo.AppendText($"文件类型：UTF-8\n");
                    }
                }
                else
                {
                    RTxtFileInfo.AppendText($"文件类型：{ TxtEncoding.EncodingName }\n");
                }

                System.IO.FileInfo fileInfo = new System.IO.FileInfo(sFilePath);
                System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(sFilePath);
                this.Text = fileInfo.Name;
                RTxtFileInfo.AppendText($"文件名称：{ fileInfo.Name }\n");
                RTxtFileInfo.AppendText($"产品名称：{ info.ProductName }\n");
                RTxtFileInfo.AppendText($"公司名称：{ info.CompanyName }\n");
                RTxtFileInfo.AppendText($"文件版本：{ info.FileVersion }\n");
                RTxtFileInfo.AppendText($"产品版本：{ info.ProductVersion }\n");
                // 通常版本号显示为「主版本号.次版本号.生成号.专用部件号」
                RTxtFileInfo.AppendText($"系统显示文件版本：{ info.ProductMajorPart }.{info.ProductMinorPart}.{info.ProductBuildPart}.{info.ProductPrivatePart}\n");
                RTxtFileInfo.AppendText($"文件说明：{ info.FileDescription }\n");
                RTxtFileInfo.AppendText($"文件语言：{ info.Language }\n");
                RTxtFileInfo.AppendText($"原始文件名称：{ info.OriginalFilename }\n");
                RTxtFileInfo.AppendText($"文件版权：{ info.LegalCopyright }\n");

                RTxtFileInfo.AppendText($"文件大小：{ System.Math.Ceiling(fileInfo.Length / 1024.0) }KB");

                cCurrentCSVFile.FileName = fileInfo.Name;
                cCurrentCSVFile.FilePath = sFilePath;
                cCurrentCSVFile.FileEncoding = TxtEncoding;

                List<CCurrentCSVFileData> FileData = new List<CCurrentCSVFileData>();
                DataTable dataTable = CCSV_Operate.OpenCSV(sFilePath, TxtEncoding, out FileData);
                cCurrentCSVFile.FileData = FileData;

                DataTable ndt = new DataTable();
                DataColumn dc = new DataColumn();
                dc.ColumnName = "序号";
                dc.AutoIncrement = true;
                dc.AutoIncrementSeed = 1;
                dc.AutoIncrementStep = 1;
                ndt.Columns.Add(dc);
                ndt.Merge(dataTable);

                DGVFileData.Columns.Clear();
                DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
                checkBoxColumn.Name = "select";
                checkBoxColumn.HeaderText = "选择";
                DGVFileData.Columns.Insert(0, checkBoxColumn);
                DGVFileData.DataSource = ndt;

                DGVFileData.Columns["序号"].ReadOnly = true;

                RTxtFileNotes.Clear();
                var FileDataNotes = (from v in cCurrentCSVFile.FileData
                                     where v.RowType == 1
                                     select v).OrderBy(ob => ob.RowID).ToList();
                foreach (var FileDataNotesItem in FileDataNotes)
                {
                    if (FileDataNotesItem == FileDataNotes.Last())
                    {
                        RTxtFileNotes.AppendText($"{FileDataNotesItem.RowData}");
                    }
                    else
                    {
                        RTxtFileNotes.AppendText($"{FileDataNotesItem.RowData}\n");
                    }
                }
            }
        }

        private void BtnAddRow_Click(object sender, EventArgs e)
        {
            bool IsExist = IsExistDT();

            if (!IsExist)
            {
                return;
            }


            if (MessageBox.Show("请问需要在表格末尾处添加单行吗？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                AddRow(1);
            }
            else
            {
                FrmCSV_Editor_AddRows frmCSV_Editor_AddRows = new FrmCSV_Editor_AddRows();
                if (frmCSV_Editor_AddRows.ShowDialog() == DialogResult.OK)
                {
                    string AddRowsCount = frmCSV_Editor_AddRows.AddRowsCount;
                    AddRow(Convert.ToInt32(AddRowsCount));
                }
            }
        }

        private void BtnAddColumn_Click(object sender, EventArgs e)
        {
            bool IsExist = IsExistDT();

            if (!IsExist)
            {
                return;
            }

            FrmCSV_Editor_Column frmCSV_Editor_Column = new FrmCSV_Editor_Column();
            frmCSV_Editor_Column.Text = "新增列";
            frmCSV_Editor_Column.Notes = "请在此输入待新增的列名！";
            if (frmCSV_Editor_Column.ShowDialog() == DialogResult.OK)
            {
                string ColumnName = frmCSV_Editor_Column.ColumnName;
                Editor_Column(0, ColumnName);
            }
        }

        private void BtnDelRow_Click(object sender, EventArgs e)
        {
            bool IsExist = IsExistDT();

            if (!IsExist)
            {
                return;
            }

            List<DataGridViewRow> DataGridViewRows = new List<DataGridViewRow>();
            foreach (DataGridViewRow row in DGVFileData.Rows)
            {
                if (row.Cells[0].Value != null && Convert.ToBoolean(row.Cells[0].Value) == true)
                {
                    DataGridViewRows.Add(row);
                }
            }

            if (DataGridViewRows.Count <= 0)
            {
                return;
            }

            if (MessageBox.Show($"请问需要删除选中的{DataGridViewRows.Count}行吗？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                foreach (DataGridViewRow row in DataGridViewRows)
                {
                    DGVFileData.Rows.Remove(row);
                }
            }
        }

        private void BtnDelColumn_Click(object sender, EventArgs e)
        {
            bool IsExist = IsExistDT();

            if (!IsExist)
            {
                return;
            }

            FrmCSV_Editor_Column frmCSV_Editor_Column = new FrmCSV_Editor_Column();
            frmCSV_Editor_Column.Text = "删除列";
            frmCSV_Editor_Column.Notes = "请在此输入待删除的列名！";
            if (frmCSV_Editor_Column.ShowDialog() == DialogResult.OK)
            {
                string ColumnName = frmCSV_Editor_Column.ColumnName;
                Editor_Column(1, ColumnName);
            }
        }

        private void DGVFileData_KeyDown(object sender, KeyEventArgs e)
        {
            Keys key = e.KeyCode;

            //Delete删除内容
            if (key == Keys.Delete)
            {
                dgvDel(DGVFileData);
            }

            if (e.Control != true)//如果没按Ctrl键
            {
                return;
            }

            switch (key)
            {
                case Keys.C:
                    //按下Ctrl+C复制
                    //dgvCopy(DGVFileData);
                    //MessageBox.Show("使用了复制功能！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;

                case Keys.V:
                    //按下Ctrl+V粘贴
                    dgvPaste(DGVFileData);
                    //MessageBox.Show("使用了粘贴功能！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;

                case Keys.X:
                    //按下Ctrl+V剪切
                    dgvCut(DGVFileData);
                    //MessageBox.Show("使用了剪切功能！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
            }
        }

        #region 可在dgv中复制、剪切、粘贴、删除数据
        /// <summary>
        /// DataGridView复制
        /// </summary>
        /// <param name="dgv">DataGridView实例</param>
        public static void dgvCopy(DataGridView dgv)
        {
            if (dgv.GetCellCount(DataGridViewElementStates.Selected) > 0)
            {
                try
                {
                    Clipboard.SetDataObject(dgv.GetClipboardContent());
                }
                catch (Exception MyEx)
                {
                    MessageBox.Show(MyEx.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        /// <summary>
        /// DataGridView剪切
        /// </summary>
        /// <param name="dgv">DataGridView实例</param>
        public static void dgvCut(DataGridView dgv)
        {
            dgvCopy(dgv);
            try
            {
                dgvDel(dgv);
            }
            catch (Exception MyEx)
            {
                MessageBox.Show(MyEx.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        ///<summary>
        /// DataGridView删除内容
        /// </summary>
        /// <param name="dgv">DataGridView实例</param>
        public static void dgvDel(DataGridView dgv)
        {
            try
            {
                int k = dgv.SelectedCells.Count;
                for (int i = 0; i < k; i++)
                {
                    if (dgv.SelectedCells[i].ReadOnly != true)
                    {
                        dgv.SelectedCells[i].Value = "";
                    }
                }
            }
            catch (Exception MyEx)
            {
                MessageBox.Show(MyEx.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// DataGridView粘贴
        /// </summary>
        /// <param name="dt">DataGridView数据源</param>
        /// <param name="dgv">DataGridView实例</param>
        public static void dgvPaste(DataGridView dgv)
        {
            try
            {
                //最后一行为新行
                int rowCount = dgv.Rows.Count - 1;
                int colCount = dgv.ColumnCount;
                //获取剪贴板内容
                string pasteText = Clipboard.GetText();
                //判断是否有字符存在
                if (string.IsNullOrEmpty(pasteText))
                    return;
                //以换行符分割的数组
                string[] lines = pasteText.Trim().Split('\n');
                int txtLength = lines.Length;

                //Lance.2015-12-03
                int cRowIndex = dgv.SelectedCells[0].RowIndex;
                int cColIndex = dgv.SelectedCells[0].ColumnIndex;
                for (int i = 0; i < txtLength; i++)
                {
                    string[] words = lines[i].Split('\t');
                    for (int j = 0; j < words.Length; j++)
                    {
                        if (dgv.Columns[cColIndex + j].ReadOnly != true)
                        {
                            if (words[j].Contains('\r'))
                            {
                                dgv.Rows[cRowIndex + i].Cells[cColIndex + j].Value = words[j].Replace("\r", "");
                            }
                            else
                            {
                                dgv.Rows[cRowIndex + i].Cells[cColIndex + j].Value = words[j];
                            }
                        }
                    }
                }

            }
            catch (Exception MyEx)
            {
                MessageBox.Show(MyEx.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        private void BtnGetCEncodingList_Click(object sender, EventArgs e)
        {
            CEncodingList cEncodingList = CEncodingList._instance;
            foreach (var cEncodingListItem in cEncodingList.cEncodings)
            {
                Console.WriteLine(cEncodingListItem.CodePage);
                Console.WriteLine(cEncodingListItem.Name);
                Console.WriteLine(cEncodingListItem.DisplayName);
            }
        }

        private void CBSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            if (DGVFileData.ReadOnly == true)
            {
                return;
            }

            if (CBSelectAll.Checked)
            {
                for (int i = 0; i < DGVFileData.Rows.Count; i++)
                {
                    DGVFileData[0, i].Value = true;
                }
            }
            else
            {
                for (int i = 0; i < DGVFileData.Rows.Count; i++)
                {
                    DGVFileData[0, i].Value = false;
                }
            }
        }

        private void AddRow(int RowCount = 1)
        {
            DataTable dataTable = (DataTable)DGVFileData.DataSource;

            for (int i = 0; i < RowCount; i++)
            {
                DataRow dataRow = dataTable.NewRow();
                dataTable.Rows.Add(dataRow);
            }

            DGVFileData.DataSource = dataTable;
        }

        private void Editor_Column(int Type, string ColumnName)
        {
            if (ColumnName == "序号" || ColumnName == "选择")
            {
                return;
            }

            DataTable dataTable = (DataTable)DGVFileData.DataSource;
            bool IsContainColumnName = false;
            switch (Type)
            {
                case 0:
                    IsContainColumnName = dataTable.Columns.Contains(ColumnName);

                    if (!IsContainColumnName)
                    {
                        DataColumn dc = new DataColumn(ColumnName);
                        dataTable.Columns.Add(dc);
                        DGVFileData.DataSource = dataTable;
                    }
                    else
                    {
                        MessageBox.Show("列名已存在！\n禁止新增！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case 1:
                    IsContainColumnName = dataTable.Columns.Contains(ColumnName);

                    if (IsContainColumnName)
                    {
                        dataTable.Columns.Remove(dataTable.Columns[ColumnName]);
                        DGVFileData.DataSource = dataTable;
                        DGVFileData.Sort(DGVFileData.Columns["序号"], ListSortDirection.Ascending);
                    }
                    else
                    {
                        MessageBox.Show("无法找到列名！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
            }
        }

        private bool IsExistDT()
        {
            bool IsExist = true;
            DataTable dataTable = (DataTable)DGVFileData.DataSource;

            if (dataTable == null)
            {
                IsExist = false;
            }

            return IsExist;
        }

        private void BtnSelectKeyWord_Click(object sender, EventArgs e)
        {
            bool IsExist = IsExistDT();

            if (!IsExist)
            {
                return;
            }

            //MessageBox.Show("本功能待后续开发完善！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            string sSelectKeyWord = TxtSelectKeyWord.Text.Trim();
            if (string.IsNullOrEmpty(sSelectKeyWord))
            {
                return;
            }
            LVSelectKeyWord.Items.Clear();
            DataTable dataTable = (DataTable)DGVFileData.DataSource;
            DataTable ndt = new DataTable();
            ndt.Merge(dataTable);
            ndt.Columns.Remove(ndt.Columns["序号"]);
            int iLVSelectKeyWordCount = 0;
            foreach (var dtColumnsItem in ndt.Columns)
            {
                string ColumnName = dtColumnsItem.ToString();
                for (int i = 0; i < ndt.Rows.Count; i++)
                {                    
                    if (ndt.Rows[i][ColumnName].ToString().Contains(sSelectKeyWord))
                    {
                        iLVSelectKeyWordCount++;
                        LVSelectKeyWord.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度
                        ListViewItem lvi = new ListViewItem();
                        lvi.Text = iLVSelectKeyWordCount.ToString();
                        lvi.SubItems.Add(ColumnName);
                        lvi.SubItems.Add(i.ToString());//lvi.SubItems.Add(dvItem.GetType().GetProperty("rowID", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).ToString());
                        LVSelectKeyWord.Items.Add(lvi);
                        LVSelectKeyWord.EndUpdate();  //结束数据处理，UI界面一次性绘制。
                    }
                }
            }

            if(LVSelectKeyWord.Items.Count > 0)
            {
                LVSelectKeyWord.Items[0].Selected = true;
            }
        }

        private void BtnNewFile_Click(object sender, EventArgs e)
        {
            NewFile();
        }
        private void NewFile()
        {
            DataTable dataTable = new DataTable();
            DataTable ndt = new DataTable();
            DataColumn dc = new DataColumn();
            dc.ColumnName = "序号";
            dc.AutoIncrement = true;
            dc.AutoIncrementSeed = 1;
            dc.AutoIncrementStep = 1;
            ndt.Columns.Add(dc);
            ndt.Merge(dataTable);

            DGVFileData.Columns.Clear();
            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.Name = "select";
            checkBoxColumn.HeaderText = "选择";
            DGVFileData.Columns.Insert(0, checkBoxColumn);
            DGVFileData.DataSource = ndt;

            DGVFileData.Columns["序号"].ReadOnly = true;
            cCurrentCSVFile = new CCurrentCSVFile();
        }

        private void BtnSaveFile_Click(object sender, EventArgs e)
        {
            SaveFile();
        }
        private void SaveFile()
        {
            bool IsExist = IsExistDT();

            if (!IsExist)
            {
                return;
            }

            if (string.IsNullOrEmpty(cCurrentCSVFile.FileName) && string.IsNullOrEmpty(cCurrentCSVFile.FilePath))
            {
                SaveAsFile();
                return;
            }

            SaveData();
        }

        private void BtnSaveAsFile_Click(object sender, EventArgs e)
        {
            SaveAsFile();
        }

        private void SaveAsFile()
        {
            bool IsExist = IsExistDT();

            if (!IsExist)
            {
                return;
            }

            //string localFilePath, fileNameExt, newFileName, FilePath; 
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            //设置文件类型 
            saveFileDialog.Filter = "文本文件|*.csv";

            //设置默认文件类型显示顺序 
            saveFileDialog.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            saveFileDialog.RestoreDirectory = true;

            //设置默认的文件名

            saveFileDialog.FileName = "YourFileName";// in wpf is  sfd.FileName = "YourFileName";

            //点了保存按钮进入 
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string localFilePath = saveFileDialog.FileName.ToString(); //获得文件路径 
                string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1); //获取文件名，不带路径

                cCurrentCSVFile.FilePath = localFilePath;
                cCurrentCSVFile.FileName = fileNameExt;

                string sCBBDataEncoding = CBBDataEncoding.SelectedItem.ToString();
                if (sCBBDataEncoding == "UTF-8-BOM")
                {
                    cCurrentCSVFile.FileEncoding = new UTF8Encoding(true);
                }
                else if (sCBBDataEncoding == "UTF-8")
                {
                    cCurrentCSVFile.FileEncoding = new UTF8Encoding(false);
                }
                else
                {
                    try
                    {
                        cCurrentCSVFile.FileEncoding = Encoding.GetEncoding(sCBBDataEncoding);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                        cCurrentCSVFile.FileEncoding = Encoding.Default;
                    }
                }
            }
            else
            {
                return;
            }

            if (string.IsNullOrEmpty(cCurrentCSVFile.FileName) && string.IsNullOrEmpty(cCurrentCSVFile.FilePath))
            {
                MessageBox.Show("请设置需要保存的文件名及路径！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            SaveData();
        }

        private void SaveData()
        {
            DataTable dataTable = (DataTable)DGVFileData.DataSource;
            DataTable ndt = new DataTable();
            ndt.Merge(dataTable);
            ndt.Columns.Remove(ndt.Columns["序号"]);

            string FileNotes = RTxtFileNotes.Text;
            if (!string.IsNullOrEmpty(FileNotes))
            {
                CCSV_Operate.SaveCSV(cCurrentCSVFile.FilePath, RTxtFileNotes.Text, cCurrentCSVFile.FileEncoding, System.IO.FileMode.Create);
                CCSV_Operate.SaveCSV(ndt, cCurrentCSVFile.FilePath, cCurrentCSVFile.FileEncoding, System.IO.FileMode.Append);
            }
            else
            {
                CCSV_Operate.SaveCSV(ndt, cCurrentCSVFile.FilePath, cCurrentCSVFile.FileEncoding, System.IO.FileMode.Create);
            }

            MessageBox.Show("保存成功！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void TxtSelectKeyWord_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)Keys.Enter)
            {
                BtnSelectKeyWord_Click(null, null);
            }
        }

        private void 新建文件ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            NewFile();
        }

        private void 打开文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFile();
        }

        private void 保存文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFile();
        }

        private void 另存为文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveAsFile();
        }

        private void BtnShowOriginalData_Click(object sender, EventArgs e)
        {
            if (cCurrentCSVFile.FileData == null)
            {
                return;
            }
            FrmCSV_EditorOriginalData frmCSV_EditorOriginalData = new FrmCSV_EditorOriginalData();
            frmCSV_EditorOriginalData.cCurrentCSVFile = cCurrentCSVFile;
            frmCSV_EditorOriginalData.ShowDialog();
        }

        private void LVSelectKeyWord_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (LVSelectKeyWord.SelectedItems.Count > 0)
            {
                string RowNum = LVSelectKeyWord.SelectedItems[0].SubItems[2].Text;
                int RowIndex = Convert.ToInt32(RowNum);
                DGVFileData.ClearSelection();
                DGVFileData.CurrentCell = null;
                DGVFileData.Rows[RowIndex].Selected = true;
                DGVFileData.FirstDisplayedScrollingRowIndex = RowIndex;
            }
        }

        private void BtnRowNum_Click(object sender, EventArgs e)
        {
            bool IsExist = IsExistDT();

            if (!IsExist)
            {
                return;
            }

            string RowNum = TxtRowNum.Text;

            if(!string.IsNullOrEmpty(RowNum))
            {
                try
                {
                    int RowIndex = Convert.ToInt32(RowNum);
                    DGVFileData.ClearSelection();
                    DGVFileData.CurrentCell = null;
                    DGVFileData.Rows[RowIndex].Selected = true;
                    DGVFileData.FirstDisplayedScrollingRowIndex = RowIndex;
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void TxtRowNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            //数字0~9所对应的keychar为48~57
            e.Handled = true;
            //输入0-9
            if ((e.KeyChar >= 47 && e.KeyChar <= 58) || e.KeyChar == 8)
            {
                e.Handled = false;
            }
            else if (e.KeyChar == (Char)Keys.Enter)
            {
                BtnRowNum_Click(null, null);
            }
        }
    }
}
